import "dart:convert";

import 'package:ct_pa_majordomo/config/theme_vars.dart';
import 'package:ct_pa_majordomo/pages/device/lock/api.dart';
import 'package:ct_pa_majordomo/pages/widgets/menu_block.dart';
import 'package:ct_pa_majordomo/state/common.dart';
import "package:ct_pa_majordomo/utils/stacker.dart";
import 'package:ct_pa_majordomo/widgets/normal_scaffold/index.dart';
import 'package:ct_pa_majordomo/widgets/divider/solid_divider.dart';
import "package:flutter/cupertino.dart";
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:provider/provider.dart';
import "package:ttlock_flutter/ttlock.dart";

class AutoLock extends StatefulWidget {
  final Map info;
  const AutoLock({super.key, required this.info});

  @override
  State<AutoLock> createState() => _AutoLockState();
}

class _AutoLockState extends State<AutoLock> {
  bool _isEnabled = false;
  int _selectedSeconds = 5;
  bool _isCustom = false;
  final TextEditingController _customSecondsController = TextEditingController();
  
  final List<int> _presetSeconds = [5, 10, 15, 30, 60];

  @override
  void initState() {
    super.initState();
    final lockInfo = Provider.of<CommonState>(context, listen: false).lockInfo ?? {};
    final autoLockTime = lockInfo["autoLockTime"] ?? 0;
    
    setState(() {
      _isEnabled = autoLockTime > 0;
      if (_isEnabled) {
        _selectedSeconds = autoLockTime;
        if (!_presetSeconds.contains(autoLockTime)) {
          _isCustom = true;
          _customSecondsController.text = autoLockTime.toString();
        }
      }
    });
  }

  void _refreshLockInfo() {
    lockApi.getLockInfo(int.parse(widget.info["lockId"])).then((res) {
      if (mounted) {
        Provider.of<CommonState>(context, listen: false).setLockInfo(res["data"] ?? {});
        Map lockInfo = jsonDecode(res["data"]["lockInfo"]) ?? {};
        Provider.of<CommonState>(context, listen: false).setLockInfo(lockInfo);
      }
    });
  }

  void _handleSave() async {
    if (_isEnabled && _selectedSeconds == 0) {
      EasyLoading.showInfo("请填写闭锁时间");
      return;
    };
    
    try {
      EasyLoading.show();
      await lockApi.setAutoLock(
          int.parse(widget.info["lockId"]),
          {
            "lockId": widget.info["lockId"],
            "seconds": _isEnabled ? _selectedSeconds : 0,
            "changeType": 2,
          }
      );
      _refreshLockInfo();
      EasyLoading.showSuccess("设置已保存");
      Stacker.pop();
      return;
    } catch (e) {
      EasyLoading.showError("保存失败");
      TTLock.setLockAutomaticLockingPeriodicTime(_isEnabled ? _selectedSeconds : 0, widget.info["lockData"], () async {
        await lockApi.setAutoLock(
            int.parse(widget.info["lockId"]),
            {
              "lockId": widget.info["lockId"],
              "seconds": _isEnabled ? _selectedSeconds : 0,
              "changeType": 1,
            }
        );
        _refreshLockInfo();
        EasyLoading.showSuccess("设置已保存");
        Stacker.pop();
      }, (code, error) async {
        // 错误信息
        print("$code: >>>$error");
      });
    }
  }

  Widget _buildTimeSelector() {
    if (!_isEnabled) return const SizedBox();

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Padding(
          padding: EdgeInsets.symmetric(vertical: 8),
          child: Text('当前时间', style: TextStyle(color: ThemeVars.colorTextSec)),
        ),
        Container(
          child: Wrap(
            spacing: 12,
            runSpacing: 12,
            children: [
              ..._presetSeconds.map((seconds) => _buildTimeOption(seconds)),
              _buildCustomOption(),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildTimeOption(int seconds) {
    final isSelected = !_isCustom && _selectedSeconds == seconds;
    return InkWell(
      onTap: () {
        setState(() {
          _isCustom = false;
          _selectedSeconds = seconds;
        });
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        decoration: BoxDecoration(
          color: isSelected ? ThemeVars.colorPrimary : Colors.transparent,
          border: Border.all(color: isSelected ? ThemeVars.colorPrimary : ThemeVars.colorBorder),
          borderRadius: BorderRadius.circular(4),
        ),
        child: Text(
          '${seconds}s',
          style: TextStyle(
            color: isSelected ? Colors.white : ThemeVars.colorText,
          ),
        ),
      ),
    );
  }

  Widget _buildCustomOption() {
    return _isCustom
        ? Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            decoration: BoxDecoration(
              border: Border.all(color: ThemeVars.colorPrimary),
              borderRadius: BorderRadius.circular(4),
            ),
            width: 100,
            child: Row(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Expanded(
                  child: TextField(
                    controller: _customSecondsController,
                    keyboardType: TextInputType.number,
                    decoration: const InputDecoration(
                      isDense: true, // 使输入框紧凑
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.zero,
                    ),
                    style: const TextStyle(
                      fontSize: 14,
                      height: 1, // 文字行高，以更好地控制文本垂直对齐
                    ),
                    onChanged: (value) {
                      setState(() {
                        _selectedSeconds = value.isNotEmpty ? int.parse(value) : 0;
                      });
                    },
                  ),
                ),
                const Text('s', style: TextStyle(color: ThemeVars.colorText)),
              ],
            ),
          )
        : InkWell(
            onTap: () {
              setState(() {
                _isCustom = true;
                _customSecondsController.text = _selectedSeconds.toString();
              });
            },
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              decoration: BoxDecoration(
                border: Border.all(color: ThemeVars.colorBorder),
                borderRadius: BorderRadius.circular(4),
              ),
              child: const Text('自定义', style: TextStyle(color: ThemeVars.colorText)),
            ),
          );
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: '自动闭锁',
      actions: [
        TextButton(
          onPressed: _handleSave,
          child: const Text('保存', style: TextStyle(color: Colors.white)),
        ),
      ],
      child: ListView(
        padding: const EdgeInsets.all(ThemeVars.paddingPage),
        children: [
          MenuBlock(
            items: [
              MenuBlockItem(
                text: '自动闭锁',
                showArrow: false,
                suffix: CupertinoSwitch(
                  value: _isEnabled,
                  activeColor: ThemeVars.colorPrimary,
                  onChanged: (value) {
                    setState(() {
                      _isEnabled = value;
                    });
                  },
                ),
              ),
            ],
          ),
          _buildTimeSelector(),
          const Padding(
            padding: EdgeInsets.symmetric(vertical: 8),
            child: Text(
              "锁被打开后，将会在以上设定的时间后自动关闭",
              style: TextStyle(fontSize: 12, color: ThemeVars.colorTextTer),
            ),
          ),
        ],
      ),
    );
  }
} 